<template>
	<view class="container-chat">
		<scroll-view class="chat-info" scroll-y="true" :scroll-into-view="scrollInto"  @scrolltoupper="scrollTop($event)">
			<view v-for="(item,index) in list" :key="index" :id="'item'+index">
				<view class="other" v-if="item.sendRole===0">
					<view>
						<image :src="shopinfo ? baseUrl+shopinfo.shopCover : customerservice" class="avatar" @click="photoCircle(item.userId)"></image>
					</view>
					<view class="content">
						<text v-if="item.msgType == '0'">{{item.msg}}</text>
						<image  v-if="item.msgType == '1'" class="img" :src="cover" @tap="preivewImageBtn(cover)"></image>
						<view v-if="item.msgType == '2'" class="file" @click="openDocument">
							<uni-icons type="folder-add" size="18"></uni-icons>
							<text style="font-weight: 600;">{{item.fileName}}</text>
							<uni-icons type="arrow-down" size="18"></uni-icons>
						</view>
					</view>
				</view>
				<view class="self" v-else>
					<view class="contentright">
						<text v-if="item.msgType == '0'">{{item.msg}}</text>
						<image v-if="item.msgType == '1'"  :src="cover"></image>
						<view v-if="item.msgType == '2'" class="file" @click="openDocument">
							<uni-icons type="folder-add" size="18"></uni-icons>
							<text style="font-weight: 600;">{{item.fileName}}</text>
							<uni-icons type="arrow-down" size="18"></uni-icons>
						</view>
					</view>
					<view>
						<image :src="baseUrl+loginuser.avatar"  class="avatar"></image>
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="bottom">
			<view  class="send">
				<uni-easyinput clearable="true"
				style="border-radius: 5px;"
				placeholder="文明发言"  @input="changeBtn" @clear="clearBtn" v-model="msg"></uni-easyinput>
			</view>
			<view  class="sendbtn" >
				<button size="mini" type="primary"v-if="btnShow" @click="sendMsg">发送</button>
			</view>
		</view>
		<loginDialog></loginDialog>
	</view>
</template>

<script lang="ts" setup>
	import customerservice from '@/static/image/customerservice.png'
	import { onLoad } from '@dcloudio/uni-app';
	import {pageChat} from '@/api/chat.ts'
	import { nextTick, ref,watchEffect } from 'vue';
	import loginDialog from '@/pages/personcenter/login.vue'
	import {baseUrl} from '@/api/request.ts'
	import { socket } from '@/utils/websocket';
	import {info} from '@/api/shop.ts'
	
	const scrollTop=(event)=>{
		console.log("滚动到顶部",event)
		queryParams.value.page++;
		getList()
	}
	const msg=ref('')
	const btnShow=ref(false)
	const changeBtn=(e)=>{
		if(e){
			btnShow.value=true
		}else{
			btnShow.value=false
		}
	}
	const clearBtn=()=>{
		btnShow.value=false
	}
	const photoCircle=(userId)=>{
		uni.navigateTo({
			url:"/pages/my/photocircle/index?userId="+userId
		})
	}
	const preivewImageBtn=(item)=>{
			// 预览图片
			uni.previewImage({
				urls: [item],
				longPressActions: {
					itemList: [],
					success: function(data) {
						// console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
					},
					fail: function(err) {
						// console.log(err.errMsg);
					}
				}
			});
	}
	const openDocument =()=>{
		console.log("骄傲的")
		uni.downloadFile({
		  url: 'https://example.com/somefile.pdf',
	      header: {
		    'content-type': 'application/octet-stream' // 根据实际需要设置
		  },
		  success: function (res) {
			  console.log(res)
		    var filePath = res.tempFilePath;
		    uni.openDocument({
		      filePath: filePath,
		      showMenu: true,
		      success: function (res) {
		        console.log('打开文档成功');
		      }
		    });
		  },
		  fail: function(e) {
		  	console.log("下载失败"+e)
		  }
		});
	}
	const list = ref([
	])
	const total=ref(0)
	const queryParams=ref({
		page:1,
		limit:10,
	})
	const scrollInto=ref()
	const getList=()=>{
		pageChat(queryParams.value).then(res=>{
			if(queryParams.value.page==1){
				list.value=res.data.list;
				list.value.reverse()		
				const lastItemIndex = list.value.length -1;
				scrollInto.value='item'+lastItemIndex;
			}else{
				res.data.list.reverse()
				list.value=res.data.list.concat(list.value)
				scrollInto.value='item0';
			}
			total.value=res.data.total
			
		})
	}
	const cover = ref('https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/shuijiao.jpg')
	const token = uni.getStorageSync('token')
	const loginuser=uni.getStorageSync('user')
	const shopId=ref()
	const goodsId=ref()
	const orderId=ref()
	onLoad((option)=>{
		if(!uni.getStorageSync('token')){
			console.log("ho")
			uni.setStorageSync('login',true)
		}
		shopId.value=option.shopId
		goodsId.value=option.goodsId
		orderId.value=option.orderId
		if(shopId.value){
			queryParams.value.shopId=shopId.value
			getShop()
		}
		if(goodsId.value){
			queryParams.value.goodsId=goodsId.value
		}
		if(orderId.value){
			queryParams.value.orderId=orderId.value
		}
		getList()
	})
	watchEffect(()=>{
		if(shopId.value){
			queryParams.value.shopId=shopId.value
			getShop()
		}
		if(goodsId.value){
			queryParams.value.goodsId=goodsId.value
		}
		if(orderId.value){
			queryParams.value.orderId=orderId.value
		}
	})
	const shopinfo=ref()
	const getShop=()=>{
		info(shopId.value).then(res=>{
			shopinfo.value=res.data
		})
	}
	const sendMsg=()=>{
		if(!msg){
			uni.showToast({
				title:'消息不能为空'
			})
			return
		}
		if(goodsId.value){
			socket.value.send({data:JSON.stringify({"customerMsg":msg.value,"shopId":shopId.value,"msgType":'0','goodsId':goodsId.value,'chatObj':'0'})});
		}else if(orderId.value){
			socket.value.send({data:JSON.stringify({"customerMsg":msg.value,"shopId":shopId.value,"msgType":'0',
			'orderId':orderId.value,'chatObj':'1'})});
		}else{
			//用户在消息列表给店铺发送消息
			socket.value.send({data:JSON.stringify({"customerMsg":msg.value,"shopId":shopId.value,"msgType":'0',
			'chatObj':'2'})});
		}
		msg.value='' 
	}
	socket.value.onMessage((event)=>{
		console.log("二次进入",event)
		if(event.data!='ok'){
			const msgBody = JSON.parse(event.data)
			if(parseInt(msgBody.minappUserId) === parseInt(loginuser.id)){
					list.value.push(msgBody)
					total.value++;
					const lastItemIndex = list.value.length -1;
					scrollInto.value='item'+lastItemIndex;
			}
		}
	})
</script>

<style lang="scss" scoped>
	.chat-info{
		 height: 85vh;
		 // overflow: auto;
		 text-align: right;
	}
	.chat-info::-webkit-scrollbar{
		// display: none;
	}
	
	.file{
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100%;
		border: 1px solid whitesmoke;
		background-color: cornsilk;
		border-radius: 5px;
		padding: 1%;
	}
	.bottom{
		background-color: #ffffff;
		position: fixed;
		bottom: 0;
		width: 100%;
		text-align: center;
		display: flex;
		justify-content: center;
		align-items: center;
		flex-direction: row;
		border: 1px solid lightgray;
		border-radius: 2px;
		height: auto;
		padding-left: 5px;
		padding-right: 5px;
		text-align: center;
		padding-top: 15px;
		padding-bottom: 15px;
	}
	.send{
		width: 80%;
	}
	.sendbtn{
		margin-left: 2px;
		margin-right: 2px;
	}
	.sendbtn button{
		padding: 4px;
		padding-left: 6px;
		padding-right: 6px;
	}
	.content{
		width: auto;
		max-width: 40%;
		font-size: 14px;
		letter-spacing: 1px;
		background-color: white;
		padding: 2%;
		border: none;
		box-shadow: -1px 0px 5px rgba(0, 0, 0, 0.5);
		position: relative;
		margin-left: 10px;
		border-radius: 5px;
		display: flex;
		align-items: center;
		justify-content: left;
	}
	.content::before{
		   content: "";
		   position: absolute;
		   top: 10px; /* 根据需要调整 */
		   left: -15px; /* 根据需要调整 */
		   width: 0;
		   height: 0;
		   border-style: solid;
		   border-left: 10px solid transparent;
		   border-bottom: 10px solid transparent;
		   border-right: 10px solid #ffffff;
		   border-top: 10px solid transparent;
	}
	.contentright{
		width: auto;
		max-width: 40%;
		font-size: 14px;
		letter-spacing: 1px;
		background-color: white;
		padding: 2%;
		border: none;
		box-shadow: 1px 0px 5px rgba(0, 0, 0, 0.5);
		position: relative;
		margin-right: 10px;
		border-radius: 5px;
		display: flex;
		align-items: center;
		justify-content: right;
	}
	.contentright::before {
		content: "";
	   position: absolute;
	   top: 10px; /* 根据需要调整 */
	   right: -15px; /* 根据需要调整 */
	   width: 0;
	   height: 0;
	   border-style: solid;
	   border-right: 10px solid transparent;
	   border-bottom: 10px solid transparent;
	   border-left: 10px solid #ffffff;
	   border-top: 10px solid transparent;
	}
	.avatar{
		width: 40px;
		height: 40px;
		border-radius: 50%;
		margin-right: 3%;
		margin-left: 3%;
	}
	.other{
		height: auto;
		padding-left: 3px;
		padding-top: 3%;
		display: flex;
		justify-content: left;
		width: auto;
		padding-bottom: 3%;
		display: flex;
		text-align: left;
	}
	.self{
		height: auto;
		display: flex;
		padding-top: 3%;
		padding-right: 3px;
		padding-bottom: 6%;
		justify-content: right;
		margin-top: 3%;
		display: flex;
		justify-content: flex-end;
	}
	.container-chat{
		width: 100%;
		height: 100%;
	}
	.img{
		width: 100%;
		border-radius: 5px;
	}
</style>